// dragon/pages/dragonDetail/dragonDetail.js
var common = require("../../../common/common.js").common;

var leader = require("../../../common/leader.js").leader;

var shoppingCar = require("../../../common/shoppingCar.js");

var {$author: $author} = require("../../../components/base/authorization.js");

var WxParse = require("../../../wxParse/wxParse.js");

var colorParse = require("../../../common/color.js");

const app = getApp();

var util = require("../../../utils/util.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        leaderChange: false,
        //团长切换弹窗显示隐藏，false为隐藏
        currentLeaderInfo: {},
        //当前团长信息
        modalHide: true,
        //提示框显示隐藏，true影藏
        l_change: 1,
        toastHide: true,
        myleaderinfo: {
            leader_id: -1,
            leader_id_true: -1
        },
        autoplay: true,
        currentSwiper: 0,
        goods: [],
        groupRecordList: [],
        ruleModal: false,
        cartVisible: false,
        showLoadText: true,
        page: 1,
        toElementId: "",
        imgUrl: "",
        // 生成分享图链接
        transparentBg: "",
        //分享图中的背景
        info: {},
        rpx: "",
        user_info_notice: 1,
        tmplIds: [],
        //模板消息tmplIds
        subscribeMessage: true,
        openid: "",
        dSource: 1,
        cartItems: []
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        this.getHeader();
        let pagesLength = getCurrentPages().length;
        var isIPX = app.globalData.isIPX;
        let domain = app.globalData.domain.slice(0, -10);
        console.log(domain);
        that.setData({
            transparentBg: `${domain}/img/juxing.png`
        });
        that.setData({
            isIPX: isIPX,
            pagesLength: pagesLength,
            domain: domain
        });
        if (options.id) {
            that.setData({
                group_id: options.id
            });
        }
        this.setData({
            dSource: options.source ? options : 1
        });
        if (options.scene) {
            var scene = decodeURIComponent(options.scene).split(":");
            that.setData({
                group_id: scene[1]
            });
        }
        wx.getSystemInfo({
            success: function(res) {
                let rpx = res.windowWidth / 375;
                that.setData({
                    rpx: rpx,
                    deviceModel: res.model,
                    pixelRatio: res.pixelRatio
                });
            }
        });
        var cart = wx.getStorageSync(`dragon_cart_${this.data.group_id}`);
        that.getBase();
        if (app.globalData.user) {
            console.log("auto", app.globalData.user);
            that.setData({
                openid: app.globalData.user.openid
            });
            that.getMyInfo();
            leader.getMyLeaderInfo(app.globalData.user.openid, options.leader_id_share || "");
            console.log("----app----", app.globalData.user);
        } else {
            console.log("----------userInfoReadyCallback");
            app.userInfoReadyCallback = (res => {
                console.log("userInfoReadyCallbac-res", res);
                that.setData({
                    openid: res.openid
                });
                that.getMyInfo();
                leader.getMyLeaderInfo(res.openid, options.leader_id_share || "");
            });
        }
        that.getGroup();
        that.getGroupSet();
        //协议以及接龙设置
                that.getTmplIds();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        let that = this;
        var newPro = that.changeProInfo(that.data.goods);
        var newShoppingCart = shoppingCar.getDragonInfo("", this.data.group_id);
        let cart_count = 0;
        newShoppingCart.cart.map(x => {
            if (x.group_id == this.data.group_id) {
                cart_count += x.count;
            }
        });
        let bottomPadding = wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom + 94;
        //计算弹框距离底部距离
                that.setData({
            cart_count: cart_count,
            goods: newPro,
            bottomPadding: bottomPadding,
            cartList: wx.getStorageSync(`dragon_cart_${this.data.group_id}`)
        });
        that.setCartItems(wx.getStorageSync(`dragon_cart_${this.data.group_id}`));
        that.totalPrice();
    },
    //购物车列表按本地商家分组展示
    setCartItems: function(cartList) {
        console.log(cartList);
        let that = this;
        let items = JSON.parse(JSON.stringify(cartList)) || [];
        let mapObj = {}, newArr = [];
        for (var i = 0; i < items.length; i++) {
            var ai = items[i];
            if (!mapObj[ai.business_id]) {
                newArr.push({
                    business_id: ai.business_id,
                    business_name: ai.business_name,
                    items: [ ai ]
                });
                mapObj[ai.business_id] = ai;
            } else {
                // 相同的添加在一起
                for (var j = 0; j < newArr.length; j++) {
                    var dj = newArr[j];
                    if (dj.business_id == ai.business_id) {
                        dj.items.push(ai);
                        break;
                    }
                }
            }
        }
        newArr.map(i => {
            let priceTotal = 0;
            let count = 0;
            i.items.map(k => {
                priceTotal += parseFloat(k.price) * k.count;
                count += k.count;
            });
            i.count = count;
            i.priceTotal = priceTotal.toFixed(2);
        });
        console.log(items, "------", newArr);
        that.setData({
            cartItems: newArr
        });
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   *点击请下单接龙商品按钮
   */
    placeOrder: function() {
        console.log(232);
        let that = this;
        // if_order：1可以购买，0不可购买，2接龙团长身份有误
        // activity_order：活动状态是否可购买：0否，1是
                if (that.data.groupDetail.group.if_order == 0 || that.data.groupDetail.group.activity_order == 0) {
            wx.showModal({
                title: "提示",
                content: that.data.groupDetail.group.error_message,
                showCancel: false
            });
            return false;
        }
        //此处增加 本地商家商品处理开始 TODO:
                const {type: type, pro_type: pro_type, id: id} = that.data.groupDetail.group;
        //const { pro_id } = e.currentTarget.dataset.item;
                if (type == 2 && pro_type == 2) {
            let url = `/localLifePackage/pages/place_order/place_order?id=${that.data.goods[0].pro_id}&solit_id=${id}`;
            wx.navigateTo({
                url: url
            });
            return;
        }
        //此处增加 本地商家商品处理结束 TODO:
                this.setData({
            toElementId: "dragon-goods"
        });
    },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        let that = this;
        leader.getMyLeaderInfoBind(this.data.groupDetail.leader_id || "");
        that.getGroup();
        that.getGroupSet();
        that.getMyInfo();
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 获取信息
   */
    getMyInfo: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/myinfo/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                that.setData({
                    info: res.extra
                });
                that.getGroupRecord();
            }
        });
    },
    /**
   * 是否显示授权窗口
   */
    isShowAuth: function() {
        let that = this;
        if (!that.data.info.nickname || that.data.info.nickname == "" || that.data.info.nickname == "微信用户" || !that.data.info.img) {
            that.setData({
                user_info_notice: 0
            });
            return false;
        } else {
            return true;
        }
    },
    getGroupSet: function() {
        var that = this;
        common.request({
            endpoint: "group-solit/group-set",
            method: "post",
            success: res => {
                if (!res.extra.rule) {
                    res.extra.rule = "<p>暂无协议</p>";
                }
                that.setData({
                    groupSet: res.extra
                });
                WxParse.wxParse("rule", "html", res.extra.rule, that, 0);
            }
        });
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top,
            topBarWidth: menuRect.width
        });
    },
    showRuleModal: function() {
        let that = this;
        that.setData({
            ruleModal: true
        });
    },
    hideRuleModal: function() {
        let that = this;
        that.setData({
            ruleModal: false
        });
    },
    reducePopCount: function() {
        let that = this;
        let buy_count = that.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        } else {
            buy_count = 1;
        }
        that.setData({
            buy_count: buy_count
        });
    },
    /**
   * 显示底部购物车弹框
   */
    showCartModal: function() {
        let that = this;
        // 显示遮罩层
                var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        // animation.translateY(150).step()
                that.setData({
            cartVisible: true,
            animationData: animation.export(),
            cartList: wx.getStorageSync(`dragon_cart_${this.data.group_id}`) || []
        });
        this.setCartItems(wx.getStorageSync(`dragon_cart_${this.data.group_id}`));
        setTimeout(function() {
            animation.translateY(0).step();
            this.setData({
                animationData: animation.export()
            });
        }.bind(this), 200);
    },
    hideCartModal: function() {
        let that = this;
        // 隐藏遮罩层
                var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        animation.translateY(300).step();
        this.setData({
            animationData: animation.export()
        });
        setTimeout(function() {
            animation.translateY(0).step();
            this.setData({
                animationData: animation.export(),
                cartVisible: false
            });
        }.bind(this), 200);
    },
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    title: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    is_open: res.extra.is_open,
                    copyImg: res.extra.copyright_img,
                    share_link: res.extra.share_link,
                    phone: res.extra.phone,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2
                });
            }
        });
    },
    swiperChange: function(e) {
        this.setData({
            currentSwiper: e.detail.current
        });
    },
    goBack() {
        let that = this;
        wx.navigateBack({});
    },
    getGroup: function() {
        let that = this;
        common.request({
            endpoint: "group-solit/group-solit",
            method: "post",
            data: {
                group_id: that.data.group_id
            },
            success: res => {
                var goods = that.changeProInfo(res.extra[0].pro);
                var groupDetail = res.extra[0];
                if (groupDetail.group.flag == 2 && that.data.dSource == 1) {
                    wx.showModal({
                        title: "提示",
                        content: "活动已结束",
                        showCancel: false,
                        success: res => {
                            if (res.confirm) {
                                wx.switchTab({
                                    url: "/pages/index/index"
                                });
                            }
                        }
                    });
                }
                //if_order：1可以购买，0不可购买，2接龙团长身份有误
                                if (groupDetail.group.if_order == 2) {
                    wx.showModal({
                        title: "提示",
                        content: groupDetail.group.error_message,
                        showCancel: false,
                        complete: res => {
                            if (res.confirm) {
                                wx.reLaunch({
                                    url: "/pages/index/index"
                                });
                            }
                        }
                    });
                }
                groupDetail.group.img = groupDetail.group.img.split(",");
                that.setData({
                    groupDetail: groupDetail,
                    goods: goods
                });
                if (groupDetail.group.leader_id != 0) {
                    that.setData({
                        myleaderinfo: groupDetail.group.group_leader_info
                    });
                }
                leader.getMyLeaderInfoBind(groupDetail.group.leader_id || 0);
                // p1-新接龙 合并勿删
                                let contents = res.extra[0].group.content;
                if (contents) {
                    //优先展示新接龙内容
                    that.setData({
                        contents: JSON.parse(contents)
                    });
                } else {
                    that.setData({
                        rich: WxParse.wxParse("rich", "html", res.extra[0].group.detail, that, 0)
                    });
                }
                var newPro = that.changeProInfo(that.data.goods);
                var newShoppingCart = shoppingCar.getDragonInfo("", this.data.group_id);
                let cart_count = 0;
                newShoppingCart.cart.map(x => {
                    if (x.group_id) {
                        cart_count += x.count;
                    }
                });
                that.setData({
                    cart_count: cart_count
                });
                that.totalPrice();
            },
            fail(res) {
                wx.showToast({
                    icon: "none",
                    title: res.message,
                    duration: 2e3
                });
                setTimeout(() => {
                    wx.navigateTo({
                        url: "/dragon/pages/dragonList/dragonList"
                    });
                }, 2e3);
            }
        });
    },
    loadMore: function() {
        let that = this;
        that.setData({
            page: that.data.page + 1
        });
        this.getGroupRecord();
    },
    getGroupRecord: function() {
        let that = this;
        common.request({
            endpoint: "group-solit/group-record",
            method: "post",
            data: {
                group_id: that.data.group_id,
                page: that.data.page,
                size: 5,
                last_sort: that.data.groupRecordList.length == 0 ? 0 : that.data.groupRecordList[that.data.groupRecordList.length - 1]["sort_no"]
            },
            success: res => {
                let groupRecordList = that.data.groupRecordList.length ? that.data.groupRecordList : [];
                groupRecordList.push(...res.extra);
                that.setData({
                    groupRecordList: groupRecordList,
                    showLoadText: res.extra.length != 0
                });
                //授权过再绘制海报
                                if (that.isShowAuth()) {
                    if (!that.data.imgUrl) {
                        that.showShare();
                    }
                }
            },
            fail() {}
        });
    },
    goToDetail: function(e) {
        let that = this;
        if (that.data.groupDetail.group.flag == 0) {
            return false;
        }
        //如果是本地商家处理 开始 TODO:
                const {type: type, pro_type: pro_type, merchant_id: merchant_id} = that.data.groupDetail.group;
        //console.log( e.currentTarget.dataset, 'e.currentTarget.datasete.currentTarget.dataset' )
                const {pro_id: pro_id, proID: proID} = e.currentTarget.dataset.item;
        if (type == 2) {
            let url = "";
            //实物
                        if (pro_type == 1) {
                url = `/localLifePackage/pages/superMarket_detail/superMarket_detail?id=${pro_id || proID}&business_id=${merchant_id}`;
                //虚拟
                        } else if (pro_type == 2) {
                url = `/localLifePackage/pages/pro_detail/pro_detail?merchant_id=${merchant_id}&pro_id=${pro_id || proID}`;
            }
            url && wx.navigateTo({
                url: url
            });
            return;
        }
        //如果是本地商家处理 结束 TODO:
                wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    //计算购买总价
    totalPrice: function(e) {
        let that = this;
        let cart = wx.getStorageSync(`dragon_cart_${this.data.group_id}`);
        let goods = that.data.goods;
        let totalPrice = 0;
        if (cart.length) {
            cart.map(x => {
                goods.map(j => {
                    if (x.proID == j.pro_id) {
                        totalPrice = parseFloat(totalPrice) + parseFloat(x.price) * x.count;
                    }
                });
            });
        }
        that.setData({
            totalPrice: totalPrice.toFixed(2)
        });
    },
    //关闭蒙层
    close_alert: function(e) {
        this.setData({
            alert: 0
        });
    },
    //购物车
    join_cart: function(e) {
        let that = this;
        //授权过再添加购物车
                if (!that.isShowAuth()) {
            return false;
        }
        if (that.data.groupDetail.group.flag == 0) {
            wx.showModal({
                title: "提示",
                content: "接龙活动未开始,无法购买该商品",
                showCancel: false
            });
            return false;
        }
        // if_order：团长身份是否可购买：0否，1是
        // activity_order：活动状态是否可购买：0否，1是
                if (that.data.groupDetail.group.if_order == 0 || that.data.groupDetail.group.activity_order == 0) {
            wx.showModal({
                title: "提示",
                content: that.data.groupDetail.group.error_message,
                showCancel: false
            });
            return false;
        }
        if (that.data.groupDetail.group.leader_buy == 1 && that.data.myleaderinfo.iam_leader != 1) {
            wx.showModal({
                title: "提示",
                content: "您不是" + that.data.leaderName + "没有购买权限",
                showCancel: false,
                success(res) {
                    // if (res.confirm) {
                    //   wx.navigateTo({
                    //     url: '/pages/nearby_group2/nearby_group2',
                    //   })
                    // }
                }
            });
        } else {
            that.join_cart_current(e);
        }
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        //console.log(version);
                if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "21" || v.type == "22" || v.type == "23") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    },
    join_cart_current: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        /**检查商品规格 */        common.request({
            endpoint: "product/shopping-push",
            method: "post",
            data: {
                id: id,
                group_id: that.data.group_id
            },
            success: res => {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                //console.log( sku, 'skuskusku' )
                                let sku_info = this.getProductBySku(details.sku, sku);
                //console.log( sku_info, 'sku_infosku_info' )
                                that.data.goods.map(item => {
                    if (item.pro_id === details.product_id) {
                        details.business_id = item.business_id;
                        details.business_name = item.business_name;
                    }
                });
                if (single == 1) {
                    that.join_cart_current_ch(details, e);
                    if (that.data.subscribeMessage) {
                        wx.requestSubscribeMessage({
                            tmplIds: that.data.tmplIds,
                            success(res) {},
                            fail(err) {
                                console.log(err);
                            },
                            complete() {}
                        });
                    }
                } else {
                    that.setData({
                        details: details,
                        sku: sku,
                        alert: 1,
                        product_id: id,
                        sku_info: sku_info,
                        proId: id,
                        buy_count: 1,
                        spec_fund: details.spec_fund,
                        is_vip: details.is_vip,
                        vip_price: sku_info.vip_price,
                        group_id: that.data.group_id
                    });
                }
            }
        });
    },
    //单规格商品购买
    join_cart_current_ch: function(details, e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        details.sku_attribute = details.sku_attribute.map(item => {
            item.attribute_value = this.selectSingleSku(item.attribute_value);
            return item;
        });
        let sku_attribute = details.sku_attribute;
        let sku = sku_attribute.reduce((s, v) => {
            s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
            return s;
        }, "");
        let sku_info = this.getProductBySku(details.sku, sku);
        let cart_count = 0;
        let cart = wx.getStorageSync(`dragon_cart_${this.data.group_id}`);
        if (cart.length > 0) {
            let find_current_item = cart.find(item => item.id == sku_info.item_id);
            if (find_current_item) {
                cart_count = find_current_item.count;
            }
            if (sku_info.restrictions > 0 && cart_count + 1 > sku_info.restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "超出限购！",
                    showCancel: false
                });
                return false;
            }
        }
        // let cart_count = wx.getStorageSync(`dragon_cart_count_${this.data.group_id}`)
                if (cart_count <= 99999) {
            //有库存且加购数量小于库存
            if (sku_info.stock_number >= 1 && cart_count + 1 <= sku_info.stock_number) {
                wx.showToast({
                    title: "加入购物车成功",
                    icon: "none",
                    success: res => {
                        let goods = {
                            business_id: details.business_id,
                            business_name: details.business_name,
                            id: sku_info.item_id,
                            product_id: id,
                            only_express: details.only_express,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            restrictions: sku_info.restrictions,
                            count: 1,
                            stock_number: sku_info.stock_number,
                            num: sku_info.stock_number,
                            select: 1,
                            proID: id,
                            status: 1,
                            credit_sent: sku_info.credit_sent || 0,
                            spec_fund: details.spec_fund,
                            is_vip: details.is_vip,
                            vip_price: sku_info.vip_price,
                            group_id: that.data.group_id
                        };
                        let newShoppingCart = shoppingCar.addDragonPro(goods, this.data.group_id);
                        var newGoods = that.changeProInfo(that.data.goods, newShoppingCart);
                        // console.log(newShoppingCart,newGoods)
                                                that.setCartItems(newShoppingCart.cart);
                        that.setData({
                            goods: newGoods,
                            cart_count: newShoppingCart.cart_count
                        });
                        common.changeIconNum(newShoppingCart.cart_count, 2);
                        that.totalPrice();
                    }
                });
            } else {
                wx.showToast({
                    title: "库存不足",
                    icon: "none"
                });
            }
        } else {
            wx.showToast({
                title: "购物车最多加99999个商品！",
                icon: "none"
            });
        }
    },
    /** 
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /** 
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    /**
   * 商品信息修改
   */
    changeProInfo(proInfo, cartInfoParamter) {
        // console.log("商品修改")
        // console.log(proInfo)
        // console.log(cartInfoParamter)
        var cartInfo = cartInfoParamter ? cartInfoParamter.statisticsArry : shoppingCar.getDragonInfo("", this.data.group_id).statisticsArry;
        if (proInfo.length > 0) {
            proInfo.forEach((item, index) => {
                if (cartInfo.length > 0) {
                    for (var i = 0; i < cartInfo.length; i++) {
                        if (item.pro_id == cartInfo[i].product_id) {
                            item.buyCount = cartInfo[i].count;
                            break;
                        } else {
                            item.buyCount = 0;
                        }
                    }
                } else {
                    item.buyCount = 0;
                }
            });
        }
        return proInfo;
    },
    //购物车减
    reduceCount(e) {
        let that = this;
        if (that.data.groupDetail.group.if_order == 0 || that.data.groupDetail.group.activity_order == 0) {
            wx.showModal({
                title: "提示",
                content: that.data.groupDetail.group.error_message,
                showCancel: false
            });
            return false;
        }
        if (e.currentTarget.dataset.single == 1) {
            var newShoppingCart = shoppingCar.reduceDragonPro([ e.currentTarget.dataset.id ], this.data.group_id);
            var newPro = that.changeProInfo(that.data.goods);
            //改变购物车上标数量
                        that.setData({
                cart_count: newShoppingCart.cart_count,
                goods: newPro
            });
            that.totalPrice();
            // console.log(newShoppingCart,that.data.cartItems)
                        that.setCartItems(newShoppingCart.cart);
            common.changeIconNum(newShoppingCart.cart_count, 2);
        } else {
            wx.showToast({
                title: "该商品是多属性商品，请到购物车操作",
                icon: "none"
            });
        }
    },
    //加
    addCount(e) {
        let that = this;
        if (e.currentTarget.dataset.item.buyCount >= e.currentTarget.dataset.item.num) {
            wx.showModal({
                title: "提示",
                content: "库存不足,无法继续购买！",
                showCancel: false
            });
            return false;
        }
        if (e.currentTarget.dataset.item.buyCount >= e.currentTarget.dataset.item.limit && e.currentTarget.dataset.item.limit != 0) {
            wx.showModal({
                title: "提示",
                content: "超出限购！",
                showCancel: false
            });
            return false;
        }
        that.join_cart_current(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                },
                complete() {}
            });
        }
    },
    /**
   * 
   * @param {弹框购物车减少操作} e 
   */
    reduce_count(e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var pro_id = e.currentTarget.dataset.productid;
        var cartList = that.data.cartList;
        var cart_count = that.data.cart_count;
        var goods_index = that.data.goods.findIndex(item => item.pro_id == pro_id);
        //购物车中分组商品需重置index
                cartList.map((item, itemIndex) => {
            if (item.id == e.currentTarget.dataset.id) {
                index = itemIndex;
            }
        });
        let string = cartList[index].varieties == "默认" ? `是否确认删除${cartList[index]["title"]}?` : `是否确认删除${cartList[index]["title"]}-${cartList[index]["varieties"]}？`;
        if (cartList[index]["count"] <= 1) {
            wx.showModal({
                title: "提示",
                content: string,
                confirmText: "确认",
                success: res => {
                    if (res.confirm) {
                        cartList.splice(index, 1);
                        cart_count--;
                        that.data.goods[goods_index]["buyCount"]--;
                        that.quickSetting(cartList, cart_count, that.data.goods);
                    } else if (res.cancel) {
                        return;
                    }
                }
            });
        }
        if (cartList[index]["count"] > 1) {
            cartList[index]["count"]--;
            cart_count--;
            that.data.goods[goods_index]["buyCount"]--;
            that.quickSetting(cartList, cart_count, that.data.goods);
        }
    },
    /**
 * 
 * @param {弹框购物车增加操作} e 
 */
    addCartcount(e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var pro_id = e.currentTarget.dataset.productid;
        var cartList = that.data.cartList;
        var cart_count = that.data.cart_count;
        var goods_index = that.data.goods.findIndex(item => item.pro_id == pro_id);
        //购物车中分组商品需重置index
                cartList.map((item, itemIndex) => {
            if (item.id == e.currentTarget.dataset.id) {
                index = itemIndex;
            }
        });
        if (cartList[index]["count"] > cartList[index]["stock_number"] - 1) {
            wx.showModal({
                title: "提示",
                content: "库存不足，无法继续购买!",
                showCancel: false
            });
            return false;
        }
        if (cartList[index]["restrictions"] != 0 && cartList[index]["count"] >= cartList[index]["restrictions"]) {
            wx.showModal({
                title: "提示",
                content: "超出限购，无法购买!",
                showCancel: false
            });
            return false;
        }
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                },
                complete() {}
            });
        }
        cartList[index]["count"]++;
        cart_count++;
        that.data.goods[goods_index]["buyCount"]++;
        that.quickSetting(cartList, cart_count, that.data.goods);
    },
    /**
   * 一键设置需改变 商品等变量
   * @param {购物车弹框列表} cartList 
   * @param {*购物车商品数量} cart_count 
   * @param {*接龙详情商品数量} goods 
   */
    quickSetting(cartList, cart_count, goods) {
        this.setData({
            cartList: cartList,
            cart_count: cart_count,
            goods: goods
        });
        wx.setStorageSync(`dragon_cart_${this.data.group_id}`, cartList);
        wx.setStorageSync(`dragon_cart_count_${this.data.group_id}`, cart_count);
        common.changeIconNum(cart_count, 2);
        this.totalPrice();
        this.setCartItems(cartList);
    },
    join_goods: function() {
        let that = this;
        if (that.data.groupDetail.group.if_order == 0 || that.data.groupDetail.group.activity_order == 0) {
            wx.showModal({
                title: "提示",
                content: that.data.groupDetail.group.error_message,
                showCancel: false
            });
            return false;
        }
        that.join_goods_ch();
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                },
                complete() {}
            });
        }
    },
    join_goods_ch: function() {
        var that = this;
        var alert = that.data.alert;
        var cart_count = wx.getStorageSync(`dragon_cart_count_${this.data.group_id}`) || 0;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var id = that.data.product_id;
        cart_count = cart_count + buy_count;
        var cart = wx.getStorageSync(`dragon_cart_${this.data.group_id}`) || [];
        if (cart_count <= 99999) {
            if (sku_info.stock_number >= buy_count) {
                if (cart == "") {
                    let goods = {
                        business_id: details.business_id,
                        business_name: details.business_name,
                        id: sku_info.item_id,
                        only_express: details.only_express,
                        product_id: id,
                        img: details.icon_img,
                        title: details.name,
                        varieties: sku_info.title,
                        price: sku_info.price,
                        o_price: sku_info.o_price,
                        count: buy_count,
                        stock_number: sku_info.stock_number,
                        select: 1,
                        proID: id,
                        status: 1,
                        credit_sent: sku_info.credit_sent || 0,
                        //赠送积分
                        spec_fund: details.spec_fund,
                        restrictions: details.restrictions,
                        is_vip: details.is_vip,
                        vip_price: sku_info.vip_price,
                        group_id: that.data.group_id
                    };
                    wx.showToast({
                        title: "加入购物车成功",
                        icon: "none",
                        success: res => {
                            wx.setStorageSync(`dragon_cart_count_${this.data.group_id}`, cart_count);
                            this.setData({
                                cart_count: cart_count,
                                pro_share: false
                            });
                            common.changeIconNum(cart_count, 2);
                            var cart = wx.getStorageSync(`dragon_cart_${this.data.group_id}`) || that.data.cart;
                            if (!cart) {
                                cart = [];
                            }
                            cart.push(goods);
                            wx.setStorageSync(`dragon_cart_${this.data.group_id}`, cart);
                            this.setCartItems(cart);
                            setTimeout(() => {
                                let newShoppingCart = shoppingCar.getDragonInfo("", this.data.group_id);
                                var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                that.setData({
                                    buy_count: 1,
                                    alert: 0,
                                    goods: newPro
                                });
                                that.totalPrice();
                            }, 500);
                        }
                    });
                } else {
                    var total = 0;
                    var index = 0;
                    for (var i = 0; i < cart.length; i++) {
                        if (sku_info.item_id != cart[i]["id"]) {
                            total++;
                        } else {
                            index = i;
                            break;
                        }
                    }
                    if (total == cart.length) {
                        let goods = {
                            business_id: details.business_id,
                            business_name: details.business_name,
                            id: sku_info.item_id,
                            product_id: id,
                            only_express: details.only_express,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            count: buy_count,
                            stock_number: sku_info.stock_number,
                            select: 1,
                            proID: id,
                            status: 1,
                            credit_sent: sku_info.credit_sent || 0,
                            spec_fund: details.spec_fund,
                            is_vip: details.is_vip,
                            restrictions: details.restrictions,
                            vip_price: sku_info.vip_price,
                            group_id: that.data.group_id
                        };
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "none",
                            success: res => {
                                wx.setStorageSync(`dragon_cart_count_${this.data.group_id}`, cart_count);
                                this.setData({
                                    cart_count: cart_count
                                });
                                common.changeIconNum(cart_count, 2);
                                var cart = wx.getStorageSync(`dragon_cart_${this.data.group_id}`) || that.data.cart;
                                cart.push(goods);
                                wx.setStorageSync(`dragon_cart_${this.data.group_id}`, cart);
                                this.setCartItems(cart);
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getDragonInfo("", this.data.group_id);
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                    that.totalPrice();
                                }, 500);
                            }
                        });
                    } else {
                        cart[index]["count"] = cart[index]["count"] + buy_count;
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "none",
                            success: res => {
                                wx.setStorageSync(`dragon_cart_count_${this.data.group_id}`, cart_count);
                                this.setData({
                                    cart_count: cart_count,
                                    pro_share: false
                                });
                                common.changeIconNum(cart_count, 2);
                                wx.setStorageSync(`dragon_cart_${this.data.group_id}`, cart);
                                this.setCartItems(cart);
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getDragonInfo("", this.data.group_id);
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                    that.totalPrice();
                                }, 500);
                            }
                        });
                    }
                }
            } else {
                wx.showToast({
                    title: "加入购物车失败",
                    icon: "none"
                });
            }
        } else {
            wx.showToast({
                title: "购物车最多加99999个商品！",
                icon: "none"
            });
        }
    },
    buy: function(e) {
        var that = this;
        common.getUserInfoNew({
            success() {
                var alert = that.data.alert;
                var details = that.data.details;
                var sku_info = that.data.sku_info;
                var buy_count = that.data.buy_count;
                var id = that.data.goodsId;
                var sku_id = sku_info.item_id;
                var group_id = that.data.group_id;
                let sku_item = sku_info.item_id + "," + buy_count + "," + sku_info.credit_sent + "," + details.only_express;
                var price = "";
                if (e.currentTarget.dataset.price) {
                    price = e.currentTarget.dataset.price;
                }
                if (sku_info.stock_number >= buy_count) {
                    wx.navigateTo({
                        url: "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 0 + "&newuserprice=" + price + "&group_id=" + group_id
                    });
                    that.setData({
                        alert: 0,
                        addShoppingCar: true,
                        newUserProductPrice: ""
                    });
                } else {
                    wx.showToast({
                        title: "库存不足",
                        icon: "none"
                    });
                    that.setData({
                        alert: 0
                    });
                }
            }
        });
    },
    add_count: function(e) {
        let that = this;
        if (that.data.buy_count >= that.data.sku_info.stock_number) {
            wx.showModal({
                title: "提示",
                content: "库存不足，无法继续购买!",
                showCancel: false
            });
            return false;
        }
        if (that.data.sku_info.restrictions != 0 && that.data.buy_count >= that.data.sku_info.restrictions) {
            wx.showModal({
                title: "提示",
                content: "超出限购，无法购买!",
                showCancel: false
            });
            return false;
        }
        that.add_count_ch(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                },
                complete() {}
            });
        }
    },
    add_count_ch: function(e) {
        let that = this;
        let restrictions = e.currentTarget.dataset.restrictions;
        let buy_count = this.data.buy_count;
        if (restrictions == 0) {
            buy_count++;
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + restrictions + "份"
                });
                buy_count = restrictions;
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    allBuy: function(e) {
        let that = this;
        //授权过才可购买
                if (!that.isShowAuth()) {
            return false;
        }
        if (that.data.groupDetail.group.if_order == 0 || that.data.groupDetail.group.activity_order == 0) {
            wx.showModal({
                title: "提示",
                content: that.data.groupDetail.group.error_message,
                showCancel: false
            });
            return false;
        }
        common.getUserInfoNew({
            success() {
                if (that.data.myleaderinfo.iam_leader != 1 && that.data.groupDetail.group.leader_buy == 1) {
                    wx.showModal({
                        title: "提示",
                        content: "您不是" + that.data.leaderName + "没有购买权限",
                        showCancel: false,
                        success(res) {
                            // if (res.confirm) {
                            //   wx.navigateTo({
                            //     url: '/pages/nearby_group2/nearby_group2',
                            //   })
                            // }
                        }
                    });
                    return false;
                }
                let cart = wx.getStorageSync(`dragon_cart_${that.data.group_id}`);
                let goods = that.data.goods;
                if (!that.data.totalPrice || that.data.totalPrice == "0.00") {
                    wx.showModal({
                        title: "提示",
                        content: "请选择商品购买！",
                        showCancel: false
                    });
                    return false;
                }
                //购物车中添加多个本地商家商品：点击立即购买，页面底部弹出购物车，如弹出购物车后再次点击立即购买，弹窗提示
                                var cartItemsIndex = e.currentTarget.dataset.index;
                console.log("999999999999999", cartItemsIndex, that.data.cartItems, "----", cartItemsIndex);
                if (that.data.cartItems.length > 1 && cartItemsIndex == undefined) {
                    if (that.data.cartVisible === true) {
                        wx.showModal({
                            title: "提示",
                            content: "接龙商品在购物车中，快去结算吧",
                            showCancel: false
                        });
                    }
                    that.showCartModal();
                    return;
                }
                //去结算按钮事件
                                if (cartItemsIndex != undefined) {
                    let list = JSON.parse(JSON.stringify(that.data.cartItems)) || [];
                    cart = list[cartItemsIndex].items;
                }
                var items = [];
                cart.map(x => {
                    goods.map(j => {
                        if (x.proID == j.pro_id) {
                            items.push({
                                id: x.id,
                                count: x.count,
                                proType: j.delivery,
                                credit_sent: x.credit_sent
                            });
                        }
                    });
                });
                let sku_item = that.buildItem(items);
                console.log("111111111", cart, that.data.cartItems);
                //此处增加 本地商家商品处理 开始 TODO:
                                const {type: type, pro_type: pro_type, merchant_id: merchant_id, id: id} = that.data.groupDetail.group;
                let s_business_id = cart[0].business_id;
                console.log(type, "----------", sku_item, merchant_id, "---", s_business_id);
                //const { pro_id } = e.currentTarget.dataset.item;
                                if (type == 2) {
                    let url = "";
                    //实物商品
                                        if (pro_type == 1) {
                        url = `/localLifePackage/pages/orderPay/orderPay?sku_item=${sku_item}&id=${s_business_id}&solit_id=${id}`;
                    } else if (pro_type == 2) {
                        url = `/localLifePackage/pages/place_order/place_order?id=${that.data.goods[0].id}&solit_id=${id}`;
                    }
                    wx.navigateTo({
                        url: url
                    });
                    return;
                }
                //此处增加 本地商家商品处理 结束 TODO:
                                wx.navigateTo({
                    url: "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 1 + "&group_id=" + that.data.group_id
                });
            }
        });
    },
    buildItem: function(items) {
        return items.map(item => {
            return item.id + "," + item.count + "," + item.credit_sent + "," + item.proType;
        }).join("|");
    },
    goToUrl(e) {
        let that = this;
        if (that.data.myleaderinfo.iam_leader != 1 && that.data.groupDetail.group.leader_buy == 1) {
            wx.showModal({
                title: "提示",
                content: "您不是" + that.data.leaderName + "没有购买权限",
                showCancel: false,
                success(res) {
                    // if (res.confirm) {
                    //   wx.navigateTo({
                    //     url: '/pages/nearby_group2/nearby_group2',
                    //   })
                    // }
                }
            });
        } else {
            wx.navigateTo({
                url: e.currentTarget.dataset.url
            });
        }
    },
    callService: function(e) {
        var phone = e.currentTarget.dataset.phone;
        if (phone) {
            wx.makePhoneCall({
                phoneNumber: phone
            });
        }
    },
    //团长切换共用方法调用
    chooseButt: function(e) {
        leader.chooseButt(e);
    },
    onShareAppMessage: function(e) {
        let that = this;
        // that.data.myleaderinfo.leader_id = 303
                console.log(`/dragon/pages/dragonDetail/dragonDetail?id=${that.data.group_id}&leader_id_share=${that.data.myleaderinfo.leader_id}`);
        if (e.target && e.target.dataset.type == "detail") {
            return {
                title: that.data.groupDetail.group.name,
                imageUrl: that.data.imgUrl,
                path: `/dragon/pages/dragonDetail/dragonDetail?id=${that.data.group_id}&leader_id_share=${that.data.myleaderinfo.leader_id}`
            };
        } else {
            return {
                title: that.data.groupDetail.group.name,
                imageUrl: that.data.groupDetail.group.share_img,
                path: `/dragon/pages/dragonDetail/dragonDetail?id=${that.data.group_id}&leader_id_share=${that.data.myleaderinfo.leader_id}`
            };
        }
    },
    /**
   * 海报绘制
   */
    showShare: function() {
        let that = this;
        if (that.data.imgUrl) {
            return false;
        }
        if (that.data.groupRecordList.length) {
            // 有人参团群分享样式
            that.drawPeopleJoin();
        } else {
            // 未有人参团群分享样式
            that.drawNoPeopleJoin();
        }
    },
    // 获得canvas图片信息
    ImageInfo: function(path) {
        return new Promise((resolve, reject) => {
            wx.getImageInfo({
                src: path,
                success: function(res) {
                    resolve(res);
                },
                fail: function(res) {
                    reject(res);
                }
            });
        });
    },
    /**
  * 有人参团群分享样式
  */
    drawPeopleJoin: function() {
        let that = this;
        new Promise((resolve, reject) => {
            that.ImageInfo(this.data.info.img).then(res => {
                const ctx = wx.createCanvasContext("poster", this);
                ctx.clearRect(0, 0, 500, 400);
                const avatarWidth = 40 * that.data.rpx;
                // 绘制的头像宽度
                                const avatarHeight = 40 * that.data.rpx;
                // 绘制的头像高度
                                const avatarX = 0;
                // 绘制的头像在画布上的位置
                                const avatarY = 0;
                // 绘制的头像在画布上的位置
                                ctx.save();
                ctx.beginPath();
                // 开始绘制
                // 先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
                                ctx.arc(avatarWidth / 2 + avatarX, avatarHeight / 2 + avatarY, avatarWidth / 2, 0, Math.PI * 2, false);
                ctx.clip();
                ctx.drawImage(res.path, avatarX, avatarY, avatarWidth, avatarHeight);
                ctx.restore();
                // 恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
                                ctx.setFontSize(24);
                ctx.setFillStyle("#666");
                let nickname = that.data.info.nickname.length > 9 ? that.data.info.nickname.substr(0, 9) + "..." : that.data.info.nickname;
                ctx.fillText(nickname, 50 * that.data.rpx, 30 * that.data.rpx);
                ctx.save();
                ctx.setFontSize(24);
                ctx.setFillStyle("#666");
                //浏览量
                                let view_text = `${that.data.groupDetail.group.scan_num}人浏览`;
                ctx.fillText(view_text, 500 - ctx.measureText(view_text).width, 30 * that.data.rpx);
                let first_sort_no_y_distance = 70 * that.data.rpx;
                that.data.groupRecordList.forEach((item, index) => {
                    if (index <= 4) {
                        ctx.setFontSize(22);
                        ctx.setFillStyle("#999");
                        ctx.fillText(item.sort_no, 10 * that.data.rpx, first_sort_no_y_distance + index * 48 * that.data.rpx);
                        this.ImageInfo(item.user.icon).then(res => {
                            ctx.save();
                            const avatarWidth = 34;
                            // 绘制的头像宽度
                                                        const avatarHeight = 34;
                            // 绘制的头像高度
                                                        const avatarX = 88 * that.data.rpx;
                            // 绘制的头像在画布上的位置
                                                        const avatarY = 48 * that.data.rpx + index * 48 * that.data.rpx;
                            // 绘制的头像在画布上的位置
                                                        ctx.beginPath();
                            // 开始绘制
                                                        ctx.arc(avatarWidth / 2 + avatarX, avatarHeight / 2 + avatarY, avatarWidth / 2, 0, Math.PI * 2, false);
                            ctx.clip();
                            ctx.drawImage(res.path, avatarX, avatarY, avatarWidth, avatarHeight);
                            ctx.restore();
                            ctx.draw(true);
                            ctx.setFontSize(22);
                            ctx.setFillStyle("#333333");
                            let username = (item.user.nickname ? item.user.nickname.charAt(0) : "") + "**";
                            ctx.fillText(username, 130 * that.data.rpx, first_sort_no_y_distance + index * 49 * that.data.rpx);
                            //时间
                                                        ctx.setFontSize(22);
                            ctx.setFillStyle("#999999");
                            ctx.fillText(item.time_diff, 200 * that.data.rpx, first_sort_no_y_distance + index * 49 * that.data.rpx);
                            ctx.draw(true);
                            //商品
                                                        let good_name = (!that.data.deviceModel.includes("iPhone") ? item.product.name.slice(0, 3) : item.product.name.slice(0, 4)) + "...";
                            ctx.setFontSize(22);
                            ctx.setFillStyle("#666");
                            ctx.fillText(good_name, 320 * that.data.rpx, first_sort_no_y_distance + index * 49 * that.data.rpx);
                            ctx.draw(true);
                            //购买量
                                                        ctx.setFontSize(22);
                            ctx.setFillStyle("#EC7D40");
                            ctx.fillText(`+${item.product.num}`, 500 - ctx.measureText(`+${item.product.num}`).width, first_sort_no_y_distance + index * 49 * that.data.rpx);
                            if (index == 4) {
                                this.ImageInfo(that.data.transparentBg).then(res => {
                                    ctx.save();
                                    ctx.drawImage(res.path, 0, 234, 500, 75);
                                    ctx.restore();
                                    ctx.draw(true);
                                });
                            }
                            ctx.draw(true);
                        });
                    }
                });
                that.juxing(ctx, 0, 310, 500, 90, 8, "rgba(71, 179, 79, 1)");
                ctx.setFontSize(32);
                ctx.setFillStyle("#fff");
                ctx.fillText("立即跟团", 250 - ctx.measureText("立即跟团").width / 2, 365);
                ctx.draw(true);
            });
            resolve();
        }).then(() => {
            this.generateUrl();
            // 当页面的canvas画成功后就调取生成临时路径
                });
    },
    /**
   * 未有人参团群分享样式
   */
    drawNoPeopleJoin: function() {
        let that = this;
        let canvasW = 0;
        let canvasH = 0;
        new Promise((resolve, reject) => {
            that.ImageInfo(this.data.info.img).then(res => {
                const ctx = wx.createCanvasContext("poster", this);
                ctx.clearRect(0, 0, 500, 400);
                const avatarWidth = 40 * that.data.rpx;
                // 绘制的头像宽度
                                const avatarHeight = 40 * that.data.rpx;
                // 绘制的头像高度
                                const avatarX = 0;
                // 绘制的头像在画布上的位置
                                const avatarY = 0;
                // 绘制的头像在画布上的位置
                                ctx.save();
                ctx.beginPath();
                // 开始绘制
                // 先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
                                ctx.arc(avatarWidth / 2 + avatarX, avatarHeight / 2 + avatarY, avatarWidth / 2, 0, Math.PI * 2, false);
                ctx.clip();
                ctx.drawImage(res.path, avatarX, avatarY, avatarWidth, avatarHeight);
                ctx.restore();
                // 恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
                                ctx.setFontSize(24);
                ctx.setFillStyle("#666");
                let nickname = that.data.info.nickname.length > 9 ? that.data.info.nickname.substr(0, 9) + "..." : that.data.info.nickname;
                ctx.fillText(nickname, 50 * that.data.rpx, 30 * that.data.rpx);
                ctx.save();
                ctx.setFontSize(24);
                ctx.setFillStyle("#666");
                let view_text = `${that.data.groupDetail.group.scan_num}人浏览`;
                ctx.fillText(view_text, 500 - ctx.measureText(view_text).width, 30 * that.data.rpx);
                //p1-接龙  修改
                                let share_img = that.data.groupDetail.group.img.length > 0 ? that.data.groupDetail.group.img[0] : "";
                this.ImageInfo(share_img).then(res => {
                    //分享图使用 接龙图片第一张将1：1尺寸的图片改为2:1尺寸
                    ctx.fillStyle = "#fff";
                    ctx.save();
                    ctx.drawImage(res.path, 0, 50 * that.data.rpx, 500, 250);
                    ctx.restore();
                    //绘制矩形背景
                                        that.juxing(ctx, 12 * that.data.rpx, 190 * that.data.rpx, 220, 34, 4, "rgba(0,0,0,0.45)");
                    //文字
                                        ctx.setFontSize(22);
                    ctx.setFillStyle("#fff");
                    ctx.fillText("“一大波人正在赶来”", 20 * that.data.rpx, 214 * that.data.rpx);
                    that.juxing(ctx, 12 * that.data.rpx, 234 * that.data.rpx, 264, 34, 4, "rgba(0,0,0,0.45)");
                    //文字
                                        ctx.setFontSize(22);
                    ctx.setFillStyle("#fff");
                    ctx.fillText("“精挑好货，大家都在买”", 20 * that.data.rpx, 256 * that.data.rpx);
                    that.juxing(ctx, 0, 310, 500, 90, 8, "rgba(71, 179, 79, 1)");
                    ctx.setFontSize(32);
                    ctx.setFillStyle("#fff");
                    ctx.fillText("立即跟团", 250 - ctx.measureText("立即跟团").width / 2, 365);
                    ctx.draw(true);
                });
            });
            resolve();
        }).then(() => {
            this.generateUrl();
            // 当页面的canvas画成功后就调取生成临时路径
                });
    },
    /**
   * 绘制矩形
   * @param {canvas} ctx3 
   * @param {*} x 
   * @param {*} y 
   * @param {*矩形宽} width 
   * @param {*矩形高} height 
   * @param {*圆角} radius 
   * @param {*背景色} bg 
   */
    juxing: function(ctx3, x, y, width, height, radius, bg) {
        ctx3.beginPath();
        //开始绘制路径
                ctx3.lineWidth = 5;
        //边框大小
        // 起始点:moveTo(x,y) 二次贝塞尔曲线:quadraticCurveTo('控制点x','控制点y','结束点x','结束点y') 结束点:lineTo(x,y) ;
                ctx3.moveTo(x + radius, y);
        ctx3.lineTo(x + width - radius, y);
        ctx3.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx3.lineTo(x + width, y + height - radius);
        ctx3.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx3.lineTo(x + radius, y + height);
        ctx3.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx3.lineTo(x, y + radius);
        ctx3.quadraticCurveTo(x, y, x + radius, y);
        ctx3.fillStyle = bg;
        //为圆角矩形填充颜色
                ctx3.strokeStyle = "transparent";
        //矩形边框颜色
                ctx3.closePath();
        //闭合绘制的路径
                ctx3.fill();
        //填充当前的路径,默认颜色是黑色
                ctx3.stroke();
        //绘制确切的路径
        },
    // 截取canvas生成临时路径
    async generateUrl(canvasW = 500, canvasH = 400) {
        const that = this;
        setTimeout(() => {
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 500,
                // 截取的宽度
                height: 400,
                // 截取的高度
                destWidth: 500 * that.data.pixelRatio,
                // 生成的图片宽度
                destHeight: 400 * that.data.pixelRatio,
                // 生成的图片高度
                canvasId: "poster",
                // 生成对象的canvasid
                success: function(res) {
                    that.setData({
                        imgUrl: res.tempFilePath
                    });
                    // console.log('imagePath', that.data.imgUrl)
                                },
                fail: function(res) {
                    console.log("绘制临时路径失败");
                }
            });
        }, 1e3);
        // 设置1秒定时是防止canvas画一半，一般1秒是差不多的
        },
    user_info_notice_close: function() {
        this.setData({
            user_info_notice: 1
        });
    },
    //选择头像
    onChooseAvatar(e) {
        let that = this;
        let domian = app.globalData.domain;
        var uniacid = wx.getStorageSync("uniacid");
        let avatar_img = e.detail.avatarUrl;
        wx.uploadFile({
            url: domian + "Lodger/lodger/product-img-upload",
            filePath: avatar_img,
            name: "file",
            formData: {},
            header: {
                "Content-Type": "multipart/form-data",
                uniacid: uniacid,
                listint: 1,
                type: 99
            },
            success: function(res) {
                var avatar_url = JSON.parse(res.data);
                that.setData({
                    ["info.img"]: avatar_url.extra.url
                });
                that.formSubmit(1);
            },
            fail: function(res) {
                wx.showModal({
                    title: "错误提示",
                    content: "上传图片失败，请重试",
                    showCancel: false,
                    success: function(res) {}
                });
            }
        });
    },
    changeNickname(e) {
        this.setData({
            ["info.nickname"]: e.detail.value
        });
        this.formSubmit(1);
    },
    formSubmit: function(vvv) {
        let that = this;
        let type = vvv;
        let e = {
            detail: {
                value: {
                    img: that.data.info.img,
                    nickname: that.data.info.nickname
                }
            }
        };
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "member/saveinfo",
            method: "post",
            data: {
                openid: openid,
                info: e.detail.value
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                wx.showToast({
                    title: "保存成功",
                    icon: "success",
                    success: res => {}
                });
                if (that.data.info.img && that.data.info.nickname) {
                    that.showShare();
                    that.setData({
                        user_info_notice: 1
                    });
                }
            },
            fail: res => {
                wx.showToast({
                    title: "保存失败",
                    icon: "none"
                });
            }
        });
    }
});